package handler

import (
	"emailcenter/internal/cache"
	"emailcenter/internal/discovery"
	"emailcenter/internal/mail"
	"emailcenter/internal/service"
	"emailcenter/utils/errx"
	"emailcenter/utils/resx"
	"emailcenter/utils/secret"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func VerifyUUID(ctx *gin.Context) {
	// rpc 发起执行缓存记录操作
	//userServiceClient := ctx.Keys["user"].(service.UserServiceClient)
	//resp, err := userServiceClient.UUIDExec(ctx, &service.ExecUUIDRequest{Uuid: ctx.Query("key")})
	userConn := discovery.UserDiscover.Get()
	if userConn == nil {
		ctx.JSON(200, resx.GinResp(resx.SystemErr, errx.CtpError(errx.RpcError)))
		return
	}
	userServiceClient := service.NewUserServiceClient(userConn)
	rpcResp, err := userServiceClient.UUIDExec(ctx, &service.ExecUUIDRequest{Uuid: ctx.Query("key")})
	if rpcResp.GetCode() == 14 {
		discovery.UserDiscover.Sad(userConn.Target())
	}
	if err != nil {
		ctx.JSON(200, resx.GinResp(resx.SystemErr, err))
		return
	}
	if rpcResp.Code != 1200 {
		ctx.JSON(200, resx.GinResp(resx.Fail, rpcResp.Code))
		return
	}
	ctx.JSON(200, resx.GinResp(resx.Success, nil))
	return
}

func GenerateCaptcha(ctx *gin.Context) {
	// 获取请求数据
	var data GenerateCaptchaRequest
	ctx.BindJSON(&data)

	// TODO 找到一次性处理方法. option 1: use ShouldBind(); option 2: Abort() X; option 3: A+R
	// 鉴别数据
	if data.Operate == "" || data.Email == "" {
		ctx.JSON(200, resx.GinResp(resx.BadRequest, nil))
		return
	}

	// 记录缓存
	captcha := secret.GenerateCaptchaSimple()
	// TODO 配置化
	cache.RedisDB.Set("email:"+data.Operate+":"+data.Email, captcha, 3*time.Minute)

	// 发送验证码邮件
	err := mail.SendMailWithCaptcha(
		data.Email,
		strconv.Itoa(captcha),
		data.Operate,
	)
	if err != nil {
		ctx.JSON(200, resx.GinResp(resx.SystemErr, nil))
		return
	}
	ctx.JSON(200, resx.GinResp(resx.Success, nil))
	return
}

type GenerateCaptchaRequest struct {
	Email   string `json:"email" binding:"required"`
	Operate string `json:"operate" binding:"required"`
}
